<?php

namespace backend\modules\business\controllers;

use backend\controllers\AdminController;
use backend\modules\business\models\BusinessPig;
use common\components\Upload;
use common\models\business\BusinessBackpig;
use Yii;
use common\models\business\BusinessBackpigFinish;
use backend\modules\business\models\BusinessBackpigFinishSearch;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * BackpigFinishController implements the CRUD actions for BusinessBackpigFinish model.
 */
class BackpigFinishController extends AdminController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all BusinessBackpigFinish models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BusinessBackpigFinishSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single BusinessBackpigFinish model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $allorder = (new Query())->select('id,number,status,backfinishid,backprice')->from(BusinessBackpig::tableName())
            ->where(['backfinishid'=>$model->id])
            ->all();

        //取出结算单要打印的内容
        $print = [];
        if(empty(!$allorder)){
            $ids = ArrayHelper::getColumn($allorder,'id');
            $print = (new Query())->select('backpig.*,pig.cost as buycost')->from(BusinessBackpig::tableName().' as backpig')
                ->leftJoin(BusinessPig::tableName().' as pig','pig.id=backpig.pigid')->where(['backpig.id'=>$ids])->all();
        }
        return $this->render('view', [
            'model' => $model,
            'print' => $print
        ]);
    }

    /**
     * Creates a new BusinessBackpigFinish model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BusinessBackpigFinish();

        if ($model->load(Yii::$app->request->post())) {

            if(false !== $photo = Upload::upload($model,'file')){
                $model->setAttribute('file',$photo);
            }
            if($model->save()){
                $backids = Yii::$app->request->post('backids');
                Yii::$app->db->createCommand()->update(BusinessBackpig::tableName(),['backfinishid'=>$model->id],'id in ('.$backids.')')->execute();
                return $this->redirect(['view', 'id' => $model->id]);
            }

            return $this->dialog($this->checkError($model));
        } else {
            $getids = Yii::$app->request->get('ids');
            if(empty($getids)){
                $ids = [];
            }else{
                $ids = explode(',',$getids);
            }

            $allorder = (new Query())->select('id,number,status,farmerid,backfinishid,backprice')->from(BusinessBackpig::tableName())
                ->where(['id'=>$ids])
                ->all();

            $ischong = array_unique(ArrayHelper::getColumn($allorder,'farmerid'));
            if(count($ischong) >= 2){
                return $this->dialog("一次只能对一个农户进行结算");
            }
            $backprice = 0;
            foreach ($allorder as $key => $row){
                if($row['status'] != BusinessBackpig::STATUS_AGREE){
                    return $this->dialog('未审核的单不能就算');
                }
                if(!empty($row['backfinishid'])){
                    return $this->dialog('“'.$row['number'].'”已结算的单不能二次结算');
                }
                $backprice += $row['backprice'];
            }


            //取出结算单要打印的内容
            $ids = explode(',',$getids);
            $print = [];
            if(!empty($ids)){
                $print = (new Query())->select('backpig.*,pig.cost as buycost')->from(BusinessBackpig::tableName().' as backpig')
                    ->leftJoin(BusinessPig::tableName().' as pig','pig.id=backpig.pigid')->where(['backpig.id'=>$ids])->all();
            }

            return $this->render('create', [
                'model' => $model,
                'allorder' => $allorder,
                'backprice' => $backprice,
                'print' => $print
            ]);
        }
    }

    /**
     * Updates an existing BusinessBackpigFinish model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);


        if ($model->load(Yii::$app->request->post())) {

            $model->setScenario('update');
//            if(false !== $photo = Upload::upload($model,'file')){
//                $model->setAttribute('file',$photo);
//            }

            if($model->save()){
                return $this->redirect(['view', 'id' => $model->id]);
            }

            return $this->dialog($this->checkError($model));
        }  else {

            $allorder = (new Query())->select('id,number,status,backfinishid,backprice')->from(BusinessBackpig::tableName())
                ->where(['backfinishid'=>$model->id])
                ->all();

            //取出结算单要打印的内容
            $print = [];
            if(empty(!$allorder)){
                $ids = ArrayHelper::getColumn($allorder,'id');
                $print = (new Query())->select('backpig.*,pig.cost as buycost')->from(BusinessBackpig::tableName().' as backpig')
                    ->leftJoin(BusinessPig::tableName().' as pig','pig.id=backpig.pigid')->where(['backpig.id'=>$ids])->all();
            }

            return $this->render('create', [
                'model' => $model,
                'allorder' => $allorder,
                'backprice' => $model->totalbackprice,
                'print' => $print
            ]);

        }
    }


    /**
     * Deletes an existing BusinessBackpigFinish model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the BusinessBackpigFinish model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return BusinessBackpigFinish the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BusinessBackpigFinish::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
